package com.qianfeng.smartdevice.config;

//
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼                  BUG辟易  
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  
//  


import com.qianfeng.smartdevice.cache.MenuCache;
import com.qianfeng.smartdevice.pojo.Menu;
import com.qianfeng.smartdevice.security.MySimpleUrlAuthenticationFailureHandler;
import com.qianfeng.smartdevice.security.MySuccessHandler;
import com.qianfeng.smartdevice.security.MyUserDetailService;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * Created by Jackiechan on 2022/1/14/21:23
 *
 * @author Jackiechan
 * @version 1.0
 * @since 1.0
 */
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true,jsr250Enabled = true)
@Configuration//声明这是一个配置类,相当于一个xml
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
    private MyUserDetailService myUserDetailService;

    private BCryptPasswordEncoder bCryptPasswordEncoder;

    private MySuccessHandler mySuccessHandler;

    private MySimpleUrlAuthenticationFailureHandler mySimpleUrlAuthenticationFailureHandler;

    private MenuCache menuCache;

    @Autowired
    public void setMenuCache(MenuCache menuCache) {
        this.menuCache = menuCache;
    }

    @Autowired
    public void setMySimpleUrlAuthenticationFailureHandler(MySimpleUrlAuthenticationFailureHandler mySimpleUrlAuthenticationFailureHandler) {
        this.mySimpleUrlAuthenticationFailureHandler = mySimpleUrlAuthenticationFailureHandler;
    }

    @Autowired
    public void setMySuccessHandler(MySuccessHandler mySuccessHandler) {
        this.mySuccessHandler = mySuccessHandler;
    }

    @Autowired
    public void setbCryptPasswordEncoder(BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @Autowired
    public void setMyUserDetailService(MyUserDetailService myUserDetailService) {
        this.myUserDetailService = myUserDetailService;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        //设置每个地址需要的资格
        List<Menu> allData = menuCache.getAllData();//所有的地址集合
        allData.stream().
                filter(menu -> StringUtils.hasText(menu.getUrl())&&StringUtils.hasText(menu.getPerms()))
                        .forEach(menu -> {
                            //遍历每一个需要权限的地址,将这个地址和需要的权限告诉spring security
                            try {
                                http.authorizeRequests().antMatchers(menu.getUrl()).hasAuthority(menu.getPerms());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        });



        http.formLogin().loginProcessingUrl("/suibianxie").permitAll()//springsecurity需要我们输入的账号和密码,但是不同的人的不同的登录地址不一样,所以security不需要我们自己写登录地址,只需要设置一个就可以,会自动生成
                // .successForwardUrl("/index2.html");
                .loginPage("/login.html").permitAll()//定义自己的登录页面
                .successHandler(mySuccessHandler).failureHandler(mySimpleUrlAuthenticationFailureHandler)
                .and().authorizeRequests().anyRequest().authenticated();//TODO 注意, anyRequest().authenticated();必须放在最后面,一个地址设置过一个方式后再设置就无效了,上面设置过权限的地址在这里不会修改为仅需要登录,但是如果把这行代码放在设置权限的上面,设置权限也就无效了

       // http.authorizeRequests().anyRequest().authenticated();//所有的地址都需要登录
    }


    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/users/user");//忽略地址
        super.configure(web);
     
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);
        //告诉了springsecurity怎么获取到密码,以及如何解析密码
        auth.userDetailsService(myUserDetailService).passwordEncoder(bCryptPasswordEncoder);
    }



    @Bean
    public  BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
